<?php
namespace App\Http\Controllers;

use App\Services\OrderPingppService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use JPush\Model as M;
use App\Models\TourOrder;
use App\Models\TourOrderRefund;
use App\Models\OrderRefund;
use App\Models\Order;
use App\Models\LandownersRefund;
use App\Models\LandownersRefundGoods;
use App\Models\LandownersOrder;

/**
 * 
 * pingxx控制器
 * 
 * @author maqu
 *
 */
class PingppController extends BaseController {

    /**
     * 支付回调
     * @param OrderPingppService $orderPingppService
     */
    public function postNotify(OrderPingppService $orderPingppService)
    {
        /* *
         * Ping++ Server SDK
         * 说明：
         * 以下代码只是为了方便商户测试而提供的样例代码，商户可根据自己网站需求按照技术文档编写, 并非一定要使用该代码。
         * 接入 webhooks 流程参考开发者中心：https://www.pingxx.com/docs/webhooks/webhooks
         * 该代码仅供学习和研究 Ping++ SDK 使用，仅供参考。
         */

        require base_path('vendor/pingplusplus/pingpp-php/init.php');

        $raw_data = file_get_contents('php://input');
        // 示例
        // $raw_data = '{"id":"evt_eYa58Wd44Glerl8AgfYfd1sL","created":1434368075,"livemode":true,"type":"charge.succeeded","data":{"object":{"id":"ch_bq9IHKnn6GnLzsS0swOujr4x","object":"charge","created":1434368069,"livemode":true,"paid":true,"refunded":false,"app":"app_vcPcqDeS88ixrPlu","channel":"wx","order_no":"2015d019f7cf6c0d","client_ip":"140.227.22.72","amount":100,"amount_settle":0,"currency":"cny","subject":"An Apple","body":"A Big Red Apple","extra":{},"time_paid":1434368074,"time_expire":1434455469,"time_settle":null,"transaction_no":"1014400031201506150354653857","refunds":{"object":"list","url":"/v1/charges/ch_bq9IHKnn6GnLzsS0swOujr4x/refunds","has_more":false,"data":[]},"amount_refunded":0,"failure_code":null,"failure_msg":null,"metadata":{},"credential":{},"description":null}},"object":"event","pending_webhooks":0,"request":"iar_Xc2SGjrbdmT0eeKWeCsvLhbL"}';
        Log::debug('pingxx $raw_data:'.$raw_data);

        $headers = \Pingpp\Util\Util::getRequestHeaders();
        // 签名在头部信息的 x-pingplusplus-signature 字段
        $signature = isset($headers['X-Pingplusplus-Signature']) ? $headers['X-Pingplusplus-Signature'] : NULL;
        //Log::info('$signature:'.$signature);
        // 示例
        // $signature = 'BX5sToHUzPSJvAfXqhtJicsuPjt3yvq804PguzLnMruCSvZ4C7xYS4trdg1blJPh26eeK/P2QfCCHpWKedsRS3bPKkjAvugnMKs+3Zs1k+PshAiZsET4sWPGNnf1E89Kh7/2XMa1mgbXtHt7zPNC4kamTqUL/QmEVI8LJNq7C9P3LR03kK2szJDhPzkWPgRyY2YpD2eq1aCJm0bkX9mBWTZdSYFhKt3vuM1Qjp5PWXk0tN5h9dNFqpisihK7XboB81poER2SmnZ8PIslzWu2iULM7VWxmEDA70JKBJFweqLCFBHRszA8Nt3AXF0z5qe61oH1oSUmtPwNhdQQ2G5X3g==';

        // Ping++ 公钥，获取路径：登录 [Dashboard](https://dashboard.pingxx.com)->点击管理平台右上角公司名称->开发信息-> Ping++ 公钥
        $pub_key_path = base_path('keys/pingpp_official_rsa_public_key.pem');

        $result = $orderPingppService->verify_signature($raw_data, $signature, $pub_key_path);
        Log::debug('pingxx verify_signature result:',['result'=>$result]);
        if ($result === 1) {
            // 验证通过 do nothing
        } elseif ($result === 0) {
            http_response_code(400);
            echo 'verification failed';
            exit;
        } else {
            http_response_code(400);
            Log::error("Ping＋＋回调错误：".json_encode($raw_data));
            echo 'verification error';
            exit;
        }

        $event = json_decode($raw_data, true);

        if ($event['type'] == 'charge.succeeded') {
            $charge = $event['data']['object'];
            if($orderPingppService->updateOrderWhenSucceeded($charge)){
                http_response_code(200); // PHP 5.4 or greater
            }else {
                http_response_code(400);
                echo 'order update error';
            }

        } elseif ($event['type'] == 'refund.succeeded') {
//            http_response_code(200);
//            Log::ERROR(json_encode($event));
            $refund = $event['data'];
            if($orderPingppService->updateOrderWhenRefundSucceeded($refund)){
                http_response_code(200); // PHP 5.4 or greater
            }else{
                http_response_code(400);
                echo 'order update error';
            }

        } elseif ($event['type'] == 'batch_refund.succeeded') {
            $refund = $event['data']['object']['refunds']['data'];
            if($orderPingppService->updateOrderWhenRefundSucceeded($refund)){
                http_response_code(200); // PHP 5.4 or greater
            }else{
                http_response_code(400);
                echo 'order update error';
            }
//            Log::debug("批量退款回调函数：".json_encode($raw_data));
        } else {
            /**
             * 其它类型 ...
             * - summary.daily.available
             * - summary.weekly.available
             * - summary.monthly.available
             * - transfer.succeeded
             * - red_envelope.sent
             * - red_envelope.received
             * ...
             */
            http_response_code(200);

        }
    }

    /**
     * 退款接口
     *
     * @param OrderPingppService $orderPingppService
     * @return mixed
     */
    public function postRefund(){
        /**
         * 注意事项：
         *  因为支付宝退款策略调整，退款需要输入密码，所以需要对有支付宝的订单做特殊处理
         */

        //获取参数
        $refund_object = Input::get('refund_object');
        $refund_ids = Input::get('refund_ids');
        $user_id = Input::get('user_id');
        //验证
        if(!$refund_object || !$refund_ids){
            return $this->args_invalid();
        }

        $refund_ids_arr = explode(',',$refund_ids);
        if(count($refund_ids_arr)==0){
            return $this->args_invalid();
        }

        //TODO 'landowner'
        if(!in_array($refund_object,['goods','tour','landowners','tuan'])){
            return $this->failure('功能未实现');
        }

        switch($refund_object){
            case 'goods':
                return $this->refund_goods($refund_ids,$user_id);
            case 'tour':
                return $this->refund_tour($refund_ids,$user_id);
            case 'landowners':
                return $this->refund_landowner($refund_ids,$user_id);
            case 'tuan':
                return $this->refund_tuan($refund_ids);
        }
    }

    private function refund_goods($refund_ids,$user_id){
        $refund_id = explode(',',$refund_ids);
        $order_id_list = OrderRefund::whereIn('refund_id',$refund_id)->where('refund_status',REFUND_REFUNDING)->lists('order_id');
        $wxpay_order_list_id = Order::whereIn('order_id',$order_id_list)->where('payment_code','wxPay')->where('status',TOUR_ORDER_AGREE)->select('order_id','order_sn','order_amount')->get();
        $alipay_order_list = Order::whereIn('order_id',$order_id_list)->where('payment_code','alipay')->where('status',TOUR_ORDER_AGREE)->select('order_id','order_sn','order_amount')->first();
        $alpay_size = count($alipay_order_list);
        $wxpay_size = count($wxpay_order_list_id);
        //支付宝以外
        if($wxpay_size !=0){
            foreach($wxpay_order_list_id as $value){
                $order_pingpp_service = new OrderPingppService();
                $result = $order_pingpp_service->createRefound($user_id,$value['order_id'],'',$value['order_sn'],$value['order_amount'],'');
            }
            return $result;
        }

        //支付宝退款
        if($alpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createRefound($user_id,$alipay_order_list['order_id'],'',$alipay_order_list['order_sn'],$alipay_order_list['order_amount'],'');
            return $result;
        }
    }

    private function refund_tour($refund_ids,$user_id){
        $order_id_list = TourOrderRefund::where('refund_id',$refund_ids)->where('refund_status',TOUR_REFUND_REFUNDING)->first();
        $wxpay_order_list_id = TourOrder::where('order_id',$order_id_list['order_id'])->where('payment_code','wxPay')->where('status',TOUR_ORDER_AGREE)->select('order_id','order_sn','order_amount')->first();
        $alipay_order_list = TourOrder::whereIn('order_id',$order_id_list)->where('payment_code','alipay')->where('status',TOUR_ORDER_AGREE)->select('order_id','order_sn','order_amount')->first();
        $alpay_size = count($alipay_order_list);
        $wxpay_size = count($wxpay_order_list_id);

        //支付宝以外
        if($wxpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createRefound($user_id,$wxpay_order_list_id['order_id'],'',$wxpay_order_list_id['order_sn'],$order_id_list['refund_fee'],'');
            return $result;
        }

        //支付宝退款
        if($alpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createRefound($user_id,$alipay_order_list['order_id'],'',$alipay_order_list['order_sn'],$order_id_list['refund_fee'],'');
            return $result;
        }
        if($wxpay_size == 0 && $alpay_size == 0){
            $result = array('result'=>0,'data'=>array('message'=>'订单均已退款'));
            return $result;
        }



//        $result = [];
//
//        return $this->success();

    }

    private function refund_tuan($refund_ids){
        $refund_id = explode(',',$refund_ids);
        $order_id_list = TourOrderRefund::whereIn('refund_id',$refund_id)->where('refund_status',TOUR_REFUND_REFUNDING)->lists('order_id');
        $alipay_order_list_id = TourOrder::whereIn('order_id',$order_id_list)->where('payment_code','alipay')->where('status',TOUR_ORDER_AGREE)->where('tuan_id','!=','0')->lists('order_id');
        $wxpay_order_list_id = TourOrder::whereIn('order_id',$order_id_list)->where('payment_code','wxPay')->where('status',TOUR_ORDER_AGREE)->where('tuan_id','!=','0')->lists('order_id');
        $alpay_size = count($alipay_order_list_id);
        $wxpay_size = count($wxpay_order_list_id);
        //支付宝以外
        if($wxpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createBatchRefound($wxpay_order_list_id);
            return $result;
        }
        //支付宝批量退款
        if($alpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createBatchRefound($alipay_order_list_id);
            return $result;
        }
    }

    public function refund_landowner($refund_ids,$user_id){
        $order_id_list = LandownersRefund::where('refund_id',$refund_ids)->where('refund_status',LANDOWNERS_REFUND_REFUNDING)->first();
        $wxpay_order_list_id = LandownersOrder::where('order_id',$order_id_list['order_id'])->where('payment_code','wxPay')->where('status',LANDOWNERS_REFUND_AGREE)->select('order_id','order_sn','order_amount')->first();
        $alipay_order_list = LandownersOrder::whereIn('order_id',$order_id_list)->where('payment_code','alipay')->where('status',LANDOWNERS_REFUND_AGREE)->select('order_id','order_sn','order_amount')->first();
        $alpay_size = count($alipay_order_list);
        $wxpay_size = count($wxpay_order_list_id);
        //支付宝以外
        if($wxpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createRefound($user_id,$wxpay_order_list_id['order_id'],'',$wxpay_order_list_id['order_sn'],$order_id_list['refund_fee'],'');
            return $result;
        }

        //支付宝退款
        if($alpay_size !=0){
            $order_pingpp_service = new OrderPingppService();
            $result = $order_pingpp_service->createRefound($user_id,$alipay_order_list['order_id'],'',$alipay_order_list['order_sn'],$order_id_list['refund_fee'],'');
            return $result;
        }
        if($wxpay_size == 0 && $alpay_size == 0){
            $result = array('result'=>0,'data'=>array('message'=>'订单均已退款'));
            return $result;
        }
    }

}
